﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.ProjectType;
using SportsPlatform.Helpers;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.SportBusiness.ProjectType;
using SportsPlatform.SportBusiness.ISportBusiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 项目类别服务实现类
    /// </summary>
    [RemoteService(false)]
    public class ProjectTypeService : SportsPlatformAppServiceBase, IProjectTypeService
    {
        private readonly IRepository<ProjectType, Guid> _repository;
        private readonly IRepository<UserInfo, Guid> _userRepository;

        public ProjectTypeService(IRepository<ProjectType, Guid> repository, IRepository<UserInfo, Guid> userrepository,
            IHttpContextAccessor context) : base(context)
        {
            _repository = repository;
            _userRepository = userrepository;
        }

        /// <summary>
        /// 添加项目类别
        /// </summary>
        /// <param name="addProjectTypeQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddProjectType(AddProjectTypeQuery addProjectTypeQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var res = ObjectMapper.Map<ProjectType>(addProjectTypeQuery);

                var user = await _userRepository.GetAsync(addProjectTypeQuery.CreateId);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }

                res.CreateTime = DateTime.Now;
                res.CreateUserId = user.Id;
                if (!addProjectTypeQuery.ParentId.IsNullAndEmpty())
                {
                    var Parents = await _repository.GetAllListAsync(p => p.Id == addProjectTypeQuery.ParentId.Value);
                    if (Parents.Count < 0)
                    {
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.IsSuccess = false;
                        resultDto.Message = "该分类不存在";
                        return resultDto;
                    }
                    res.ParentId = addProjectTypeQuery.ParentId;
                }

                var category = await _repository.InsertAsync(res);

                resultDto.Code = !category.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !category.IsNullAndEmpty();
                resultDto.Message = !category.IsNullAndEmpty() ? "添加成功" : "添加失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }


        /// <summary>
        /// 更新删除状态
        /// </summary>
        /// <param name="deleteProjectTypeQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> Delete(DeleteProjectTypeQuery deleteProjectTypeQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            var res = ObjectMapper.Map<ProjectType>(deleteProjectTypeQuery);
            try
            {
                var user = await _userRepository.GetAsync(deleteProjectTypeQuery.DeleteUserId);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                var Parent = await _repository.SingleAsync(p => p.Id == deleteProjectTypeQuery.Id);
                if (Parent.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "该分类不存在";
                    return resultDto;
                }
                Parent.DeleteUserId = user.Id;
                Parent.IsDeleted = true;
                Parent.DeleteTime = DateTime.Now;
                var type = await _repository.UpdateAsync(Parent);

                resultDto.Code = !type.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !type.IsNullAndEmpty();
                resultDto.Message = !type.IsNullAndEmpty() ? "删除成功" : "删除失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取所有项目类型
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<ProjectTypeDto>> GetALLType()
        {
            ResultListDto<ProjectTypeDto> resultDto = new ResultListDto<ProjectTypeDto>();
            try
            {
                var types = await _repository.GetAllListAsync(p => p.IsDeleted == false);

                resultDto.Code = types.Count > 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = types.Count > 0;
                resultDto.Message = types.Count > 0 ? "获取成功" : "获取失败";
                resultDto.Data = ObjectMapper.Map<List<ProjectTypeDto>>(types);
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 客户端分页获取项目类别信息（用于信息同步）
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetPageProjectTypeKHDDto>> GetPageProjectTypeKHD(BasePageQuery query)
        {
            PagePagingDto<GetPageProjectTypeKHDDto> pagingDto = new();
            try
            {
                var retlist = await _repository.GetAllListAsync(info => info.IsDeleted == false);
                var pageretlist = retlist.Skip(query.PageSize * (query.PageIndex - 1))
                .Take(query.PageSize).ToList();
                if (pageretlist != null && pageretlist.Count() > 0)
                {
                    pagingDto.IsSuccess = true;
                    pagingDto.Code = HttpResultCode.Success;
                    pagingDto.Message = "查询成功！";
                    pagingDto.Data = ObjectMapper.Map<List<GetPageProjectTypeKHDDto>>(pageretlist);
                    pagingDto.TotalCount = retlist.Count;
                }
                else
                {
                    pagingDto.IsSuccess = true;
                    pagingDto.Code = HttpResultCode.NotData;
                    pagingDto.Message = "未查询到数据！";
                }
            }
            catch (Exception ex)
            {
                pagingDto.IsSuccess = false;
                pagingDto.Code = HttpResultCode.Error;
                pagingDto.Message = ex.Message.ToString();
            }
            return pagingDto;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="state">状态</param>
        /// <returns></returns>
        public async Task<BaseResultDto> SetState(UpdateProjectTypeStateQuery state)
        {
            BaseResultDto resultDto = new BaseResultDto();
            var res = ObjectMapper.Map<ProjectType>(state);
            try
            {
                var user = await _userRepository.GetAsync(state.UpdateUserId);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                var Parent = await _repository.SingleAsync(p => p.Id == state.Id);
                if (Parent.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "该分类不存在";
                    return resultDto;
                }
                Parent.State = state.State;
                Parent.UpdateUserId = user.Id;
                Parent.UpdateTime = DateTime.Now;
                var type = await _repository.UpdateAsync(Parent);

                resultDto.Code = !type.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !type.IsNullAndEmpty();
                resultDto.Message = !type.IsNullAndEmpty() ? "更新状态成功" : "更新状态失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }
    }
}
